package cn.samler.diandi.api.service.impl;

import cn.samler.diandi.api.config.TencentCloudConfig;
import cn.samler.diandi.api.model.io.Response;
import cn.samler.diandi.api.service.UploadService;
import cn.samler.diandi.api.utils.ResponseBuilder;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {
    private final TencentCloudConfig tencentCloudConfig;

    UploadServiceImpl(TencentCloudConfig tencentCloudConfig) {
        this.tencentCloudConfig = tencentCloudConfig;
    }

    @Override
    public Response upload(MultipartFile file) {
        if (file == null || file.isEmpty())
            return new ResponseBuilder().failure().msg("上传失败，文件为空").build();

        String originalFilename = file.getOriginalFilename();
        if(originalFilename == null)
            new ResponseBuilder().failure().msg("original filename cannot null").build();

        try {
            // 尝试对文件进行转换，未抛出异常则是图片文件
            ImageIO.read(file.getInputStream());

            String filename = "uploads/" + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();

            COSCredentials cred = new BasicCOSCredentials(this.tencentCloudConfig.getSecretId(), this.tencentCloudConfig.getSecretKey());
            Region region = new Region(this.tencentCloudConfig.getCos().getRegion());
            COSClient client = new COSClient(cred, new ClientConfig(region));

            // 开始上传
            try {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(inputStream.available());

                PutObjectRequest objectRequest = new PutObjectRequest(this.tencentCloudConfig.getCos().getBucketName(), filename, inputStream, metadata);
                client.putObject(objectRequest);

                return new ResponseBuilder().success().msg("上传成功").data(this.tencentCloudConfig.getCos().getDomain() + filename).build();
            } catch (Exception e) {
                return new ResponseBuilder().failure().msg("上传失败").data(e).build();
            } finally {
                client.shutdown();
            }
        } catch (IOException e) {
            return new ResponseBuilder().failure().msg("非图片文件").data(e).build();
        }
    }
}
